#include "Client.h"

#include <string>
#include <iostream>

#include "RakSleep.h"

using namespace std;

Client::Client() : m_serverAddress("127.0.0.1"), m_serverPort(60000) {
	m_packetHandler = new PacketHandler;
}

void Client::execute() {
	m_Peer->Startup(1,30,&SocketDescriptor(), 1);

	m_device = createDevice(EDT_OPENGL,dimension2d<s32>(640,480),16,false,false,false,0);
    m_driver = m_device->getVideoDriver();
    m_sManager = m_device->getSceneManager();
    m_guiEnvironment = m_device->getGUIEnvironment();

    m_device->setWindowCaption(L"Hello RakNet!");    
    irr::gui::IGUIStaticText* tmp = m_guiEnvironment->addStaticText(L"Connecting to server...",
        rect<int>(10,10,200,22), true);
    
    m_sManager->addCameraSceneNode(0, vector3df(0,30,-40), vector3df(0,5,0));

    
    std::string tmpIP;
    printf("Please input a target IP.\n");
    cin>>tmpIP;
    
    m_serverAddress = tmpIP.c_str();
    
    SystemAddress sysaddr;
    sysaddr.SetBinaryAddress(m_serverAddress.c_str());
    
    printf("Connecting...");
    sysaddr.port = m_serverPort;
    m_Peer->Connect(m_serverAddress.c_str(),m_serverPort,NULL,0,0);
    do {
        printf(".");
    } while (!m_Peer->IsConnected(sysaddr,false,false));
    	
    printf("\n");
    
    tmp->setText(L"Connected!");
    
    mainLoop();
}

void Client::mainLoop() {
    while(m_device->run()) {
    	handleNetwork();
    	drawScene();
    	RakSleep(10);
    }
}

void Client::drawScene() {
    m_driver->beginScene(true, true, SColor(0,200,200,200));
    m_sManager->drawAll();
    m_guiEnvironment->drawAll();
    m_driver->endScene();
}

Client::~Client() {
	m_device->drop();
	delete m_packetHandler;
}
